import { useState, useCallback, useEffect } from 'react';

const DEFAULT_PAGINATION = {
    current: 1,
    pageSize: 10,
    total: 0
};

const useTable = (
    form,
    fetchData,
    filters,
    sorters,
    initPagination = DEFAULT_PAGINATION,
    initCollapsed = true
    // updateQuery
) => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [pagination, setPagination] = useState(initPagination);
    const [collapsed, setCollapsed] = useState(initCollapsed);
    const { current, pageSize } = pagination;

    const fetchList = useCallback(async () => {
        setLoading(true);
        const result = await fetchData({
            form,
            current,
            pageSize,
            filters,
            sorters,
            values: form.getFieldsValue()
        });
        if (result && result.data) {
            setData(result.data);
            setPagination({
                current: result.current,
                pageSize: result.pageSize,
                total: result.total
            });
            setLoading(false);
        }
        // updateQuery();
    }, [current, pageSize, JSON.stringify(filters), JSON.stringify(sorters)]);

    useEffect(() => {
        fetchList();
    }, [fetchList]);

    return {
        data,
        setData,
        pagination,
        setPagination,
        collapsed,
        setCollapsed,
        DEFAULT_PAGINATION,
        fetchList,
        loading
    };
};
export default useTable;
